var toTrain = (function ($) {
	var sourceData,newData
	var TomcatUrl = '',loginID = ''
	var process = 'start'; //'start','practice','survey','examine','homework' finish
	$.init();
	$.plusReady(function () {
	    baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}
	
	// listType:C随堂练习 R结课考核
	function getCRProblems(listType){
		var parr = sourceData['subID']+'^'+listType
		var method = 'web.INMTeaComm:FindDrillTheoryList'
		if (listType == 'C' && sourceData.classDate == '') {
			method = 'web.INMTeaComm:FindDrillProblemList'
		}else if (listType == 'R' && sourceData.ResultUseDate == ''){
			method = 'web.INMTeaComm:FindDrillProblemList'
		}
		var pdict = {'parr':parr}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':method,'params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result.msgcode != '1') {
				mui.toast(result.msg)
				return
			}
			var arr = result.data
			var countArr = [0,0,0]
			var rightCount = 0
			for (var i = 0; i < arr.length; i++) {
				var SubMode = arr[i]['SubMode']
				if (SubMode == 'S') {
					countArr[0] += 1
				}else if (SubMode == 'M'){
					countArr[1] += 1
				}else{
					countArr[2] += 1
				}
				var CorrectFlag = arr[i].CorrectFlag||''
				if (CorrectFlag+'' == '1') {
					rightCount += 1
				}
			}
			var typeStr = ''
			if (countArr[0] > 0) {
				typeStr = '单选'+countArr[0]+'题'
			}
			if (countArr[1] > 0) {
				if (typeStr != "") {
					typeStr += '，'
				}
				typeStr = '多选'+countArr[0]+'题'
			}
			if (countArr[2] > 0) {
				if (typeStr != "") {
					typeStr += '，'
				}
				typeStr = '填空'+countArr[0]+'题'
			}
			if (listType == 'C') {
				var ClassResitNum = sourceData['ClassResitNum']
				ClassResitNum = '允许考试'+(ClassResitNum=="N"?"，不限次数":(ClassResitNum + '次'))
				var str = '考试标准： '+sourceData['ClassDuration']+'分钟，'+arr.length+'题</br>'+
					'考卷题型：'+typeStr+'</br>'+
					'合格标准：'+sourceData['ClassPass']+'分及格（满分'+sourceData['ClassScore']+'分） </br>'+
					'考核时间：'+sourceData['StartDate']+'&nbsp;至&nbsp;'+sourceData['EndDate']+'</br>'+
					'重考机制： '+(sourceData['ClassResit']!='Y'?"不允许重考":ClassResitNum)
				$('#practice .examineInfo')[0].innerHTML = str
				$('#practice .scoreInfo')[0].setAttribute('data-count','答对'+rightCount+'道题，答错'+(arr.length-rightCount)+'道题，用时 '+sourceData['classUseTime'])
				if (arr.length == 0) {
					$('#practice')[0].setAttribute('data-num','0')
					$('#practice .practiceBtn')[0].style.display = 'none'
					$('#practice .examineInfo')[0].innerHTML = '考题数为0'
					return
				}
				updatePracticeUI()
			}else{
				var ResultResitNum = sourceData['ResultResitNum']
				ResultResitNum = '允许考试'+(ResultResitNum=="N"?"，不限次数":(ResultResitNum + '次'))
				var str = '考试标准： '+sourceData['ResultDuration']+'分钟，'+arr.length+'题</br>'+
					'考卷题型：'+typeStr+'</br>'+
					'合格标准：'+sourceData['ResultPass']+'分及格（满分'+sourceData['ResultScore']+'分） </br>'+
					'考核时间：'+sourceData['StartDate']+'&nbsp;至&nbsp;'+sourceData['EndDate']+'</br>'+
					'重考机制： '+(sourceData['ResultResit']!='Y'?"不允许重考":ResultResitNum)
				$('#examine .examineInfo')[0].innerHTML = str
				$('#examine .scoreInfo')[0].setAttribute('data-count','答对'+rightCount+'道题，答错'+(arr.length-rightCount)+'道题，用时 '+sourceData['classUseTime'])
				if (arr.length == 0) {
					$('#examine')[0].setAttribute('data-num','0')
					$('#examine .practiceBtn')[0].style.display = 'none'
					$('#practice .examineInfo')[0].innerHTML = '未设置考题'
					return
				}
				updateExamineUI()
			}
			
		}, function(errorStr) {
			//mui.toast('请重试')
		});
	}

	//浏览课件
	function scanClassRes(){
		$('.mui-slider-group')[0].classList.remove('start')
		var pageUrl = 'trainVideo'
		var pageType = 'look'
		if ($('#fileType')[0].innerText == 'PDF') {
			pageUrl = '../FilePreview/pdfReader'
		}
		if (sourceData['DrillStep'] == "" || sourceData['DrillStep'] == "0") {
			pageType = ''
			if (pageUrl != 'trainVideo') {
				pageType = 'train'
			}
		}
		
		var fileUrl = TomcatUrl+'/'+encodeURI(sourceData['filesUrl'])
		var webview = plus.webview.create(pageUrl+'.html', pageUrl, {
			background: '#fff',
			statusbar: {
				background: '#fff'
			}
		},{sourceData:sourceData,pageType:pageType,title:sourceData['fileName'],fileUrl:fileUrl});
		webview.show('fade-in');
		if (sourceData['DrillStep'] == "" || sourceData['DrillStep'] == "0") {
			webview.addEventListener('close',function(){
				getDrillReleaseSub(updateStartUI)
			})
		}
	}
	
	function getDrillReleaseSub(block){
		var parr = sourceData['subID']
		var pdict = {'rw':parr}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:getDrillReleaseSub','params':JSON.stringify(pdict),'type':'RecMethod'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result.msgcode != '1') {
				mui.toast(result.msg)
				return
			}
			newData = result.data
			sourceData['DrillStep'] = newData.DrillStep
			updateProcess()
			if (block) {
				block(newData)
			}
		}, function(errorStr) {
			//mui.toast('请重试')
		});
	}
	
	//签到 签退
	function signInAction(info){
		var pdict = {rw:info.rw, flag:info.flag, loginID:loginID}
		var paramDict = {'method':'web.INMTeaComm:SaveTrainSignInOut','params':JSON.stringify(pdict),'type':'Method'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			mui.toast(result.msg)
			if (result.msg.indexOf('成功')) {
				getDrillReleaseSub(function(dataDict){
					initStartUI(dataDict)
				})
			}
		}, function(errorStr) {
			mui.toast(errorStr)
		});
		
	}
	
	
	function initStartUI(dataDict){
		if (sourceData['ReleaseWay'] != 'O') { //线下
			$("#start")[0].style.background = 'var(--bgColor)'
			$('.mui-control-item[href="#start"]')[0].innerHTML = '培训考勤'
			var SignStartTime = sourceData['SignStartTime']||''
			if (dataDict) {
				SignStartTime = dataDict['SignStartTime']||''
			}
			var signHtml = ''
			if (SignStartTime != '') {
				signHtml = '<div class="signArea mui-icon mui-icon-location-filled">'+
					'<div class="signIcon"></div><div class="signInfo">'+SignStartTime+'<br>签到</div></div>';
			}
			var SignEndTime = sourceData['SignEndTime']||''
			if (dataDict) {
				SignEndTime = dataDict['SignEndTime']||''
			}
			if (SignEndTime != '') {
				signHtml += '<div class="signArea mui-icon mui-icon-location-filled">'+
					'<div class="signIcon"></div><div class="signInfo">'+SignEndTime+'<br>签退</div></div>'
			}
			if (signHtml == '') {
				signHtml = '<div class="textTip">快来扫码签到呀~~</div>'
			}
			$('#startScroll')[0].innerHTML = signHtml;
			if (process == 'start') { //签到信息
				$('#scanBtn')[0].style.display = 'inline-block'
			}
		}else{
			$('#start').on('tap','.practiceBtn',scanClassRes);
			if (process == 'start'){ //未看过课件
				$('.mui-slider-group')[0].classList.add('start')
				if (sourceData.DrillStep == '') {
					$('#start .practiceBtn')[0].innerText = '开始学习'
				}else if(sourceData.DrillStep == '0'){
					$('#start .practiceBtn')[0].innerText = '继续学习'
				}else{
					$('#start .practiceBtn')[0].innerText = '重新学习'
				}
			}else{
				$('#start .practiceBtn')[0].innerText = '重新学习'
			}
			var filesUrl = sourceData['filesUrl']
			var tempArr = filesUrl.split('.')
			var fileType = tempArr[tempArr.length -1]
			$('#fileName')[0].innerHTML = sourceData['fileName']
			if (fileType == 'mp4') {
				$('#fileType')[0].innerHTML = '视频'
				$('#studyTime')[0].innerHTML = changeSecondToTimeStr(sourceData['videoCurrentTime'])
				var video = $('#video')[0];
				video.addEventListener("loadeddata", function(){
					sourceData.videoDuration = video.duration
					$('#fileTime')[0].innerHTML = changeSecondToTimeStr(video.duration)
					var progress = Math.ceil(parseFloat(sourceData['videoCurrentTime'])*100/parseFloat(video.duration))
					if (progress > 100) {
						progress = 100
					}
					if (isNaN(progress)) {
						progress = 0
					}
					mui('#studyLenth').progressbar().setProgress(progress);
					$('#resValue')[0].innerHTML = progress+'%'
				});
				video.src = TomcatUrl+'/'+encodeURI(filesUrl)
			}else{
				$('#fileType')[0].innerHTML = 'PDF'
				$('#fileTime')[0].innerHTML = '共 '+sourceData['videoDuration']+' 页'
				$('#studyTime')[0].innerHTML = '第 '+sourceData['videoCurrentTime']+' 页'
				var progress = Math.ceil(parseFloat(sourceData['videoCurrentTime'])*100/parseFloat(sourceData['videoDuration']))
				if (progress > 100) {
					progress = 100
				}
				mui('#studyLenth').progressbar().setProgress(progress);
				$('#resValue')[0].innerHTML = progress+'%'
			}
			dealVideoQuestionTime()
			$('#start')[0].style = ''
		}
	}
	function updateStartUI(subDict){
		sourceData['videoCurrentTime'] = subDict['videoCurrentTime']
		sourceData['videoDuration'] = subDict['videoDuration']
		if (subDict.DrillStep == '1') {
			$('#start .practiceBtn')[0].innerText = '重新学习'
			process = 'practice'
		}else{
			this.innerHTML = '继续学习'
		}
		if ($('#fileType')[0].innerHTML == '视频') {
			$('#studyTime')[0].innerHTML = changeSecondToTimeStr(subDict['videoCurrentTime'])
		}else{
			$('#studyTime')[0].innerHTML = '第 '+subDict['videoCurrentTime']+' 页'
		}
		
		var progress = Math.ceil(parseFloat(subDict['videoCurrentTime'])*100/parseFloat(subDict['videoDuration']))
		if (progress > 100) {
			progress = 100
		}
		if (isNaN(progress)) {
			progress = 0
		}
		mui('#studyLenth').progressbar().setProgress(progress);
		$('#resValue')[0].innerHTML = progress+'%'
	}
	//随堂练习
	function updatePracticeUI(data){
		if ($('#practice')[0].getAttribute('data-num') == '0') {
			return
		}
		if (!data) {
			data = sourceData
		}else if (data.DrillStep == '1'&&data.classDate != '') { //考试完过来的
			//开启下一项
			gotoNextStep('2',function(){
				updateProcess('2')
				mui('#slider').slider().gotoItem(2,100)
			})
		}
		if (data.classDate == '') { //从未考试过
			return
		}
		var examineInfo = $('#practice .examineInfo')[0]
		var dateSpan = examineInfo.querySelector('span')
		if (!dateSpan) {
			examineInfo.appendChild(document.createElement('br'))
			dateSpan = document.createElement('span')
			examineInfo.appendChild(dateSpan)
		}
		dateSpan.innerHTML = '考试日期：'+data.classDate+'<br>考试次数：'+data.classUseResitNum+' 次'
		$('#practice .scoreBtns')[0].style.display="flex";
		examineInfo.classList.add('grayColor')
		
		var practiceBtn = $('#practice .practiceBtn')[0]
		var score = parseInt(data['UseClassScore']) ;
		var times = practiceBtn.getAttribute('data-time')
		if (times != 'N') {
			times = parseInt(times) - parseInt(data.classUseResitNum)
		}
		
		var infoDom = $('#practice .scoreInfo')[0]
		var html = '<div class="scoreTitle">考试成绩</div>'
		var ClassPass = data.ClassPass || sourceData.ClassPass
		if (score >= parseInt(ClassPass)) {//通过
			html += '<div class="scoreResult">通过</div>'
			//practiceBtn.style.display = 'none';
		}else if (times == "N" || parseInt(times)> 1) {//未通过可以复考
			html += '<div class="scoreResult redColor">未通过</div>'
			practiceBtn.innerHTML = '重考（'+(times == "N"?"不限次数":(times+'次'))+'）';
		}else{//复考未通过
			html += '<div class="scoreResult redColor">未通过</div>'
			practiceBtn.innerHTML = '重考（'+times+'）';
			practiceBtn.style.background = 'gray'
			practiceBtn.classList.add('noTimes')
		}	
		html += '<div class="scoreText">'+score+'<span >分</span></div>'+
			'<div class="scoreCount">'+infoDom.getAttribute('data-count')+'</div>';
		infoDom.innerHTML = html
	}
	function gotoNextStep(step,block){
		var parr = sourceData['subID']+'^'+step+'^^'
		var pdict = {'parr':parr}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:SaveDrillStep','params':JSON.stringify(pdict),'type':'Method'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msgcode'] != '1') {
				mui.toast(result.msg)
				return
			}
			sourceData['DrillStep'] = step
			if (block) {
				block()
			}
		}, function(errorStr) {
			mui.toast(errorStr)
		});
	}
	
	function getSurveyData(type){
		var pdict = {'rw':sourceData['subID'],'type':type}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:GetDrillSurvey','params':JSON.stringify(pdict),'type':'RecMethod'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msgcode'] != '1') {
				mui.toast(result.msg)
				return
			}
			var data = result.data
			//{"EvaluateDR":"3||18","RowId":"","Status":"A","StatusDesc":"未评价","SubmitDate":"","TotalScore":"","Type":"DC"}
			//{"EvaluateDR":"3||18","RowId":"","Status":"A","StatusDesc":"未评价","SubmitDate":"","TotalScore":"","Type":"DT"}
			$('#'+type)[0].setAttribute('data-rw',data.RowId)
			$('#'+type)[0].setAttribute('data-status',data.Status)
			$('#'+type +'Content')[0].innerHTML = '截止时间：'+sourceData.EndDate+'<br />'+
				'提交时间：'+data['SubmitDate']+'<br />'+
				'评价状态：'+data['StatusDesc']+'<br />'+
				'评价分数：'+data['TotalScore']
			if (data['SubmitDate'] == '') {
				$('#'+type+'Btn')[0].style.display = 'block'
			}else{
				$('#'+type+'Btn')[0].style.display = 'none'
			}
			if (sourceData.DrillStep != '2') {
				return
			}
			if ($('#DCBtn')[0].style.display == 'none' && $('#DTBtn')[0].style.display == 'none') {
				gotoNextStep('3',function(){
					updateProcess('3')
					mui('#slider').slider().gotoItem(3,100)
				})
			}
		}, function(errorStr) {
			mui.toast(errorStr)
		});
	}

	//结课考核
	function updateExamineUI(data){
		if ($('#examine')[0].getAttribute('data-num') == '0') {
			return
		}
		if (!data) {
			data = sourceData
		}else if (data.DrillStep == '1'&&data.ResultUseDate != '') { //考试完过来的
			//开启下一项
			gotoNextStep('4',function(){
				updateProcess('4')
				//mui('#slider').slider().gotoItem(4,100)
			})
		}
		if (data.ResultUseDate == '') { //从未考试过
			return
		}
		var examineInfo = $('#examine .examineInfo')[0]
		var dateSpan = examineInfo.querySelector('span')
		if (!dateSpan) {
			examineInfo.appendChild(document.createElement('br'))
			dateSpan = document.createElement('span')
			examineInfo.appendChild(dateSpan)
		}
		dateSpan.innerHTML = '考试日期：'+data.ResultUseDate+'<br>考试次数：'+data.ResultUseResitNum+' 次'
		$('#examine .scoreBtns')[0].style.display="flex";
		examineInfo.classList.add('grayColor')
		
		var practiceBtn = $('#examine .practiceBtn')[0]
		var score = parseInt(data['UseResultScore']) ;
		var times = practiceBtn.getAttribute('data-time')
		if (times != 'N') {
			times = parseInt(times) - parseInt(data.ResultUseResitNum)
		}
		var infoDom = $('#examine .scoreInfo')[0]
		var html = '<div class="scoreTitle">考试成绩</div>'
		var ResultPass = data.ResultPass || sourceData.ResultPass
		if (score >= parseInt(ResultPass)) {//通过
			html += '<div class="scoreResult">通过</div>'
			//practiceBtn.style.display = 'none';
		}else if (times == "N" || parseInt(times)>= 1) {//未通过可以复考
			html += '<div class="scoreResult redColor">未通过</div>'
		}else{//复考未通过
			html += '<div class="scoreResult redColor">未通过</div>'
			practiceBtn.style.background = 'gray'
			practiceBtn.classList.add('noTimes')
		}
		practiceBtn.innerHTML = '重考（'+(times == "N"?"不限次数":(times+'次'))+'）';
		html += '<div class="scoreText">'+score+'<span >分</span></div>'+
			'<div class="scoreCount">'+infoDom.getAttribute('data-count')+'</div>';
		infoDom.innerHTML = html
		return
		if (data['hasAsk']) { //有问答题时
			infoDom.innerHTML = '<div class="scoreTitle">答题卡</div><div class="answerSheet">'+
				'<div class="ansItem correct">1</div>'+
				'<div class="ansItem correct">2</div>'+
				'<div class="ansItem correct">3</div>'+
				'<div class="ansItem correct">4</div>'+
				'<div class="ansItem error">5</div>'+
				'<div class="ansItem correct">6</div>'+
				'<div class="ansItem error">7</div>'+
				'<div class="ansItem">8</div>'+
				'<div class="ansItem waiting">9</div>'+
				'<div class="ansItem waiting">10</div></div>';
			practiceBtn.style.display='none'
		}
	}
	
	function updateProcess(step){
		var DrillStep = sourceData['DrillStep']
		if (step != undefined) {
			DrillStep = step
		}
		var text = ''
		var btnText = ''
		var itemIndex = parseInt(DrillStep)
		switch (DrillStep){
			case '1':
				process = 'practice'
				text = '做完随堂练习才能开启哦~~'
				btnText = '去做题'
				break;
			case '2':
				process = 'survey'
				text = '做完问卷调查才能开启哦~~'
				btnText = '去做调查'
				break;
			case '3':
				process = 'examine'
				text = '做完结课考核才能开启哦~~'
				btnText = '去考核'
				break;
			case '4':
				process = 'homework'
				break;
			case '5':
				process = 'finish'
				break;
			default:
				text = '课件看完后才能开启哦~~'
				btnText = '去看课件'
				if (sourceData['ReleaseWay'] != 'O'){ //线下
					text = '签到后才能开启哦~~'
					btnText = '去签到'
				}
				itemIndex = 0
				break;
		}
		$('.mui-slider-group')[0].setAttribute('class','mui-slider-group '+process)
		if (text!= "") {
			mui('.mui-slider-group .mask').each(function() {
				this.querySelector('.textTip').innerHTML = text
				var btn = this.querySelector('.tipBtn')
				btn.innerHTML = btnText
			});
		}
	}
	function nextBtnTapped(){
		var DrillStep = sourceData.DrillStep
		var newStep = (DrillStep == ''?1:(parseInt(DrillStep)+1));
		switch (newStep){
			case 1:
				if(sourceData['ReleaseWay'] != 'O'){ //线上
					if (!$('#startScroll signInfo')[0]) {
						mui.toast('请先签到')
						return
					}
				}
				break;
			case 2:
				var classDate = (newData?newData.classDate:sourceData.classDate)
				var num = $('#practice')[0].getAttribute('data-num')
				if(num != '0' && classDate == ''){
					mui.toast('请先完成随堂练习')
					return
				}
				break;
			case 3:
				if(sourceData['StudentClassDR']!=""&& $('#DCBtn')[0].style.display != 'none'){
					mui.toast('请先完成评价')
					return
				}
				if(sourceData['StudentTeacherDR']!="" && $('#DTBtn')[0].style.display != 'none'){
					mui.toast('请先完成评价')
					return
				}
				break;
			case 4:
				var num = $('#examine')[0].getAttribute('data-num')
				var ResultUseDate = (newData?newData.ResultUseDate:sourceData.ResultUseDate)
				if(num != '0' && ResultUseDate == ''){
					mui.toast('请先完成结课考核')
					return
				}
				break;
			case 5:
				
				break;
			default:
				break;
		}
		gotoNextStep(newStep+'',function(){
			sourceData.DrillStep = newStep+''
			updateProcess(newStep+'')
			if (newStep != 5) {
				mui('#slider').slider().gotoItem(newStep,100)
			}
		})
	}
	function baseSetup(){
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		//其它页面调转当前页面
		mui('#slider').on('tap','.tipBtn',scrollToCurrProcess)
		//签到
		$('body').on('tap','#scanBtn',function(){
			createWithoutTitle('../HomePages/barcode_scan.html', {
				titleNView: {
					backgroundColor: '#fff',
					titleText: '扫一扫',
					titleColor: '#000',
					titleSize: '15px',
					autoBackButton: true,
					buttons: [{
						text: '相册',
						fontSize: '15px',
						onclick: 'javascript:scanPicture()',
					}]
				},
			});
		}); 
		var self = plus.webview.currentWebview()
		sourceData = self.sourceData
		//console.log(sourceData.DrillStep)
		// sourceData.DrillStep = '5'
		$('.mui-title')[0].innerText = sourceData['ReleaseDesc']
		//console.log(JSON.stringify(sourceData))
		updateProcess()
		$('.mui-slider-group')[0].setAttribute('class','mui-slider-group '+process)
		var perInfo = app.getState()
		TomcatUrl = perInfo.TomcatUrl
		loginID = perInfo.loginID
		initStartUI()
		//随堂练习 重考次数
		$('#practice .practiceBtn')[0].setAttribute('data-time',sourceData.ClassResitNum==""?0:sourceData.ClassResitNum);
		getCRProblems('C')
		//滚动当前进度
		scrollToCurrProcess();
		
		$('#practice').on('tap','.practiceBtn',function(){
			if (this.getAttribute('class').indexOf('noTimes') !=-1) {
				mui.toast('考试次数用完')
				return;
			}
			var webview = plus.webview.create('examRealPaper.html', 'examRealPaper', {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			},{pageType:'practice',fromPage:'toTrain',sourceData:sourceData,typeFlag:'C'});
			webview.show('fade-in');
			webview.addEventListener('close',function(){
				getDrillReleaseSub(updatePracticeUI)
			});
		});
		//问卷调查
		if (sourceData['StudentClassDR']!="") {
			getSurveyData('DC')
		}else{
			$('#DC')[0].style.display = 'none'
			$('#DCBtn')[0].style.display = 'none'
		}
		if (sourceData['StudentTeacherDR']!="") {
			getSurveyData('DT')
		}else{
			$('#DT')[0].style.display = 'none'
			$('#DTBtn')[0].style.display = 'none'
		}
		//如果没有评价 直接跳过
		if (sourceData.DrillStep == '2' && sourceData['StudentClassDR']==""&&sourceData['StudentTeacherDR']=="") {
			gotoNextStep('3',function(){
				updateProcess('3')
				mui('#slider').slider().gotoItem(3,100)
			})
		}
		
		$('#survey').on('tap','.mui-card',function(){
			var surverId = this.id
			var rw = this.getAttribute('data-rw')
			var status = this.getAttribute('data-status')
			var surveyBtn = this.querySelector('.baseBtn');
			var webview = plus.webview.create('surveyPaper.html', 'surveyPaper', {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			},{fromPage:'toTrain',sourceData:sourceData,surverType:surverId,rw:rw,status:status});
			webview.show('fade-in');
			webview.addEventListener('close',function(){
				if (sourceData['StudentClassDR']!="") {
					getSurveyData('DC')
				}
				if (sourceData['StudentTeacherDR']!="") {
					getSurveyData('DT')
				}
			});
		});
		//结课考核 重考次数
		getCRProblems('R')
		$('#examine .practiceBtn')[0].setAttribute('data-time',sourceData.ResultResitNum==""?0:sourceData.ResultResitNum);
		$('#examine').on('tap','.practiceBtn',function(){
			if (this.getAttribute('class').indexOf('noTimes') !=-1) {
				mui.toast('考试次数用完')
				return;
			}
			var webview = plus.webview.create('examRealPaper.html', 'examRealPaper', {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			},{pageType:'classEndExam',fromPage:'toTrain',sourceData:sourceData,typeFlag:'R'});
			webview.show('fade-in');
			webview.addEventListener('close',function(){
				getDrillReleaseSub(updateExamineUI)
			});
		});
		//课后作业
		$('#homeworkInfo')[0].innerHTML = sourceData.HomeworkDesc+'（ '+sourceData['HomeworkPass']+'分及格，满分'+
			sourceData['HomeworkScore']+'分 ）。'
		$('#homeworktime')[0].innerHTML = '作业上交截至时间：'+sourceData.HomeworkDateTime
		$('#addImgBtn').on('change','input',homeWorkAddImage);
		$('#homework').on('tap','.practiceBtn',function(){
			//上传完成
			mui.toast('上传完成')
		});
		//错题解析
		mui('.analysisBtn').each(function() {
			this.addEventListener('tap',analysisBtnTapped);
		});
		mui('#slider').on('tap','.nextBtn',nextBtnTapped) 
		//console.log($('.mui-slider-group')[0].outerHTML)
	}

	function scrollToCurrProcess(){
		var index = sourceData.DrillStep
		if (index == '' || index == '5') {
			index = 0
		}else{
			index = parseInt(index)
		}
		mui('#slider').slider().gotoItem(index,100)
	}
	
	function analysisBtnTapped(){
		var activeItem = $('#sliderHead .mui-control-item.mui-active')[0].innerText
		var pageType = 'practice'
		var typeFlag = 'C'
		if (activeItem != '随堂练习') {
			pageType = 'classEndExam'
			typeFlag = 'R'
		}
		var allAnaly = true
		if (this.innerText.indexOf('所有') == -1) {
			allAnaly = false
		}
		var webview = plus.webview.create('examRealPaper.html', 'examRealPaper', {
			background: '#fff',
			statusbar: {
				background: '#fff'
			}
		},{pageType:pageType,fromPage:'toTrain',isAnaly:true,allAnaly:allAnaly,sourceData:sourceData,typeFlag:typeFlag});
		webview.show('fade-in');
	}
	
	function homeWorkAddImage(){
		var addImgBtn = $('#addImgBtn')[0]
		var homeImages = $('#homework .homeImages')[0]
		for (var i = 0; i < this.files.length; i++) {
			var URL = window.URL || window.webkitURL;
			var imgURL = URL.createObjectURL(this.files[i]);
			var imgDiv = document.createElement('div');
			imgDiv.classList.add('imgDiv')
			imgDiv.innerHTML = '<div class="mui-icon mui-icon-closeempty deleteTip"></div><img src="'+imgURL+'" >'
			homeImages.insertBefore(imgDiv,addImgBtn);
			imgDiv.querySelector('.deleteTip').addEventListener('tap',function(){
				var homeImages = $('#homework .homeImages')[0]
				homeImages.removeChild(this.parentNode);
				if (!homeImages.querySelector('.imgDiv')) {
					$('#homework .practiceBtn')[0].style.display = 'none'
				}
			})
		}
		// inputFiles.push(this.files[0]);
		if (homeImages.querySelector('.imgDiv')) {
			$('#homework .practiceBtn')[0].style.display = 'block'
		}
	}
	
	function changeSecondToTimeStr(second){
		if (second == '') {
			second = 0
		}
		var timeStr = ''
		var secondInt = Math.ceil(second)
		var hour = Math.floor(secondInt/3600)
		if (hour != 0) {
			timeStr = hour+'小时'
		}
		secondInt = secondInt%3600
		var minute = Math.floor(secondInt/60)
		if (minute != 0) {
			timeStr += minute+'分钟'
		}
		secondInt = secondInt%60
		if (timeStr == '' || secondInt != 0) {
			timeStr += secondInt+'秒'
		}
		return timeStr
	}
	function dealVideoQuestionTime(){
		var times = sourceData['videoQuestion'].split('「')
		if (sourceData['videoQuestion'] == '') {
			times = []
		}
		var count = times.length
		$('#quesCount')[0].innerHTML = '共'+count+'题'
		var str = ''
		for (var i = 0; i < times.length; i++) {
			var oneTime = times[i]
			if (oneTime == '') {
				continue
			}
			var timeStr = oneTime.split('」')[0]
			if (timeStr == '') {
				continue
			}
			if (str != '') {
				str += '， '
			}
			str += timeStr
		}
		$('#quesTimes')[0].innerHTML = str
	}
	var scanSuccess = function(info){
		if (typeof info == 'string') {
			info = JSON.parse(info)
		}
		var type = info.flag+''
		var typeText = '签到'
		if (type == '1') {
			typeText = '签退'
		}
		if (info.rw != sourceData['rw']) {
			mui.confirm('非本课程的'+typeText+'码？','温馨提示',['确定'],function (e) {},'div')
			return
		}
		mui.confirm('确认'+typeText+sourceData['ReleaseDesc']+'吗？',typeText+'提示',['取消',typeText],function (e) {
			if (e.index == 1) {
				signInAction(info)
			}
		},'div')
	}
	var exporObj={}
	exporObj.scanSuccess = scanSuccess
	return exporObj
})(mui);

function setToTrainInfo(str,typeFlag){
	if (typeFlag == 'R') {
		mui('#examine .scoreInfo')[0].setAttribute('data-count',str)
	}else{
		mui('#practice .scoreInfo')[0].setAttribute('data-count',str)
	}
}
function scaned(type, result, file) {
	toTrain.scanSuccess(result)
	plus.io.resolveLocalFileSystemURL('_doc/barcode/', function(entry) {
		entry.removeRecursively(function() {}, function(e) {});
	});
}


/*
{
	"rw": "9",
	"AutoScoreType": "Y",		// 结课标准-手动授予分数时自动带入学分
	"CheckWork": "",			// 课程考勤-考勤R签到/O签退 选项
	"ChildVideoInfo": "9@%Library.RelationshipObject",	//DHCINM.Tea.DrillVideoInfo 提问/评论/点赞
	"ClassDraw": "Y",			// 是否固定组卷
	"ClassDuration": "",		// 随堂练习-考核时长
	"ClassPaperType": "I",		// 随堂练习-出卷方式
	"ClassPass": "",			// 随堂练习-及格成绩
	"ClassQuesRange": "",		// 随堂练习-出卷范围
	"ClassQuesRangeI": "",		// 随堂练习-出卷范围,固定组卷题库
	"ClassResit": "Y",			// 随堂练习-是否允许重考
	"ClassResitNum": "",		//// 随堂练习-重考次数
	"ClassScore": "",			// 随堂练习-题目总分
	"ClassType": "",			//随堂练习-隶属项目
	"CoursesType": "Y", 		//是否选修 Y必修 N选修
	"CreatDate": "2023-10-11",	//创建时间
	"CreatTime": "38732",		//创建时间
	"Creator": "468",			//创建人
	"DrillCharge": "173",		// 负责人
	"DrillCredit": "3",			//学分
	"DrillCreditType": "A",		//学分方式
	"DrillPerNum": "",			// 人数上线
	"DrillScore": "3",			// 结课标准-授予分数
	"EndDate": "2024-10-18",	//结束日期
	"Examinee": "护士层级",		// 考核人群类别
	"ExamineeList": "19||2,19||3,19||4,19||5",	// 考核人群类型
	"ExamineeWard": "1,3,4,5,6,7",	//考核人群病区
	"ExamineeListDesc": "护士层级:N1,N2,N3,N4",
	"ExamineeWardDesc": "呼吸与危重症病房（本部）,心内一病房（本部）,心内二病房（本部）,心内三病房（本部）,心内四病房（本部）,心内五病房（本部）",
	"Examiner": "81",			//讲师
	"HomeworkDateTime": "2023-10-12 10:43",	// 课后作业-课后作业上交截至时间
	"HomeworkDesc": "",			// 课后作业-课后作业描述
	"HomeworkPass": "",			// 课后作业-课后作业及格分
	"HomeworkScore": "",		// 课后作业-课后作业总分
	"QRCode": "S",				// 课程考勤-考勤二维码，S:静态吗，T:动态码
	"ReleaseDesc": "培训主题测试",	// 考核主题
	"ReleaseDrillType": "49||7",	// 培训类型
	"ReleaseLevel": "H",			// 考核级别H:院级,L:科级,W:病区
	"ReleaseWay": "O",				// 培训方式：O线上，D:线下
	"ResultDraw": "Y",				// 是否固定组卷
	"ResultDuration": "10",			// 结课考核-考核时长
	"ResultExaminer": "468",		// 结课考核-考官
	"ResultMode": "T",				// 结课考核-隶属类型
	"ResultPaperType": "I",			// 结课考核-理论-出卷方式
	"ResultPass": "6",				// 结课考核-及格成绩
	"ResultQuesRange": "S」」10」1」10」1,4",	// 结课考核-理论-考核范围
	"ResultQuesRangeI": 			// 结课考核-理论-考核范围，固定组卷题库
		举例:"4||1」1「4||10」1「4||11」1「4||12」1「4||2」1「4||3」1「4||4」1「4||5」1「4||6」1「4||9」1",
	"ResultResit": "Y",				// 结课考核-是否允许重考
	"ResultResitNum": "3",			// 结课考核-重考次数
	"ResultScore": "10",			// 结课考核-理论-考核总分
	"ResultTimeList": "",			// 结课考核-考核时间
	"ResultType": "54||1",			// 结课考核-隶属项目
	"ReulstOperationRange": "",		// 结课考核-基操-考核范围
	"StartDate": "2023-10-11",		//开始日期
	"Status": "Y",					// 状态:N/"":保存,Y:发布,
	"StudentClassDR": "7",			// 问卷调查-学员对课程评价DC
	"StudentTeacherDR": "8",		// 问卷调查-学员对讲师的评价内容DT
	"TeacherStudentDR": "9",		// 问卷调查-讲师对学员的评价内容DS
	"TimeList": "",					// 课程信息--课程批次
	"dirllFileSubDR": "1",			// 课件--课件库文件id
	"fileDownFlag": "Y",			// 课件--是否可下载
	"fileName": "非暴力沟通.pdf",	// 课件--文件名称
	"filesOfFile": "",				// 课件--上传到文件库全路径id
	"filesUrl": "Fileupdate/images/drillFile/6/非暴力沟通.pdf",	// 课件--上传文件地址
	"finishStand": "2",				// 结课标准-课程完成标准
	"passStand": "",				// 结课标准-课程通过标准
	"videoPass": "",				// 视频插题--合格数
	"videoQuestion": "",			// 视频插题--试题
	"orderList": "79",				//预约---
	"startStatus": "Y",				//N未开始 Y已开始 E已结束
	"OrderFlag": "Y",				// 是否已预约
	"subID": "9||79",
	"DrillResult": "",				// 培训结果【未完成、已通过、已完成？？？】
	"DrillStep": "1",				// 学习进度
	"OrderNum": "1",				// 预约批次
	"Remark": "",					//备注
	"ResultOpeUseDate": "",			// 结课考核基操考核日期
	"ResultOpeUseOrderTime": "",	// 结课考核基操预约批次
	"ResultOpeUseScore": "",		// 结课考核基操考核成绩
	"ResultOpeUseTime": "",			// 结课考核基操考核用时
	"ResultUseDate": "",			// 结课考核日期
	"ResultUseResitNum": "",		// 结课考核考试次数
	"ResultUseTime": "",			// 结课用时
	"ScoreUsedFlag": "",			// 成绩是否计入统计:Y：是，N:否
	"SignEndTime": "",				// 签退时间
	"SignStartTime": "",			// 签到时间
	"UseClassScore": "",			// 随堂练习得分
	"UseDrillScore": "",			// 授予学分状态
	"UseDrillScoreStatus": "",		// 授予学分状态
	"UseHomeworkScore": "",			// 课后作业得分
	"UseHomeworkScoreStatus": "",	// 课后作业状态
	"UseResultScore": "",			// 结课考核得分
	"UserDR": "468",				//人员id
	"WardDR": "1",					//病区
	"classDate": "",				// 随堂考核日期
	"classUseResitNum": "",			// 随堂练习考试次数
	"classUseTime": "",				// 随堂用时
	"videoAnswerNum": "",			// 视频插题答题数量
	"videoCurrentTime": "",			// 视频进度
	"videoDuration": "",			// 视频长度
	"videoRightNum": "",			// 视频插题答对数量
	"ExceptionDR": "",				// 异常说明
	"HomeworkUrl": "",				// 课后作业上传文件
	"perNo": "0528",
	"perName": "臧阳爽",
	"wardDesc": "呼吸与危重症病房（本部）",
	"SignData": "签到,签退",			//签到信息
	"UseStatusDesc1": "未完成",		//签到	未完成或已通过
	"videoTimeRate": "0%",			//视频进度  
			i obj.videoCurrentTime'="" d
			.s videoTimeRate=$fn(obj.UseHomeworkScore/obj.videoCurrentTime*100,0)
			s:videoTimeRate>=90 UseStatusDesc2="已完成"
			s:videoTimeRate>=95 UseStatusDesc2="已通过"
	"UseStatusDesc2": "未完成",		//视频进度 未完成 已完成 已通过
	"UseStatusDesc3": "已通过",		//视频插题 未完成 已完成 已通过
	"UseStatusDesc4": "未完成",		//随堂练习 未完成 已完成 已通过
	"DrillUseSurveyStatus": "未提交",	//问卷调查 未提交 提交
	"UseStatusDesc5": "未完成",			//文件调查结果 未完成 已通过
	"UseStatusDesc6": "未完成",			//节课考核 未完成 已完成 已通过
	"UseStatusDesc7": "已通过",			//课后作业 未完成 已完成 已通过
	"DrillResultDesc": "未完成"			//培训结果--整体结果
}
*/
